//
//  QuestionListViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/19.
//

#import "QuestionListViewController.h"
#import "QuestionListTableCell.h"
#import "QuestionSectionView.h"

#define kTabCell     @"kTabCell"

#define kFootViewHeight  (15 + 48 + (IS_IPhoneX_All ? kHeight_BottomSafe : 15))

@interface QuestionListViewController ()

@property (nonatomic) NSMutableArray *changeArr;

@property (nonatomic) UIView *headView;

@end

@implementation QuestionListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)initFootView{
    
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kFootViewHeight - kNavigationBarHeight, kScreenWidth, kFootViewHeight)];
    bottomV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomV];
    
    UIButton *footBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth - 30, 48)];
    footBtn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:15];
    [footBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [footBtn setTitleColor:kWhiteColor forState:UIControlStateSelected];
    [footBtn setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [footBtn setTitle:@"Submit" forState:UIControlStateNormal];
    [footBtn setTitle:@"Submit" forState:UIControlStateSelected];
    [footBtn setTitle:@"Submit" forState:UIControlStateHighlighted];
    [footBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [footBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [footBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
    [footBtn addTarget:self action:@selector(clickSubmit) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:footBtn];
    [footBtn setImgRightTitltLeft:10];
    footBtn.backgroundColor =  kButtonDefaultColor;
    footBtn.layer.cornerRadius = 24;
    footBtn.layer.masksToBounds = YES;
    
}

- (void)initHeadView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(158 - 30))];
    self.tableView.tableHeaderView = headView;
    self.headView = headView;
    
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(158))];
    icon.image = [UIImage imageNamed:@"icon_ques1"];
    [headView addSubview:icon];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        [tableView sendSubviewToBack:self.headView];
    }
}

- (void)viewDidLoad {
    self.isTableViewStyleGrouped = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Questionnaire";
    
    self.changeArr = [[NSMutableArray alloc] init];
    
    [self loadData];
    
    [self.tableView registerClass:[QuestionListTableCell class] forCellReuseIdentifier:kTabCell];
    
}

- (void)loadData{
    [BoxLoadingHelper showBoxLoadingWithMessage:@"" onView:self.view withOriginY:-kNavigationBarHeight];
    NSMutableDictionary *muDic = @{
//        @"question":@"questionStr"
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kQuestionListUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
       
        self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kFootViewHeight - kNavigationBarHeight);
        [self initHeadView];
        [self initFootView];
        self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
        
        
        NSDictionary *dic = responseDic[@"clip"];
        NSArray *ary = dic[@"shallow"];
    
        [self initAry:ary];
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
    } withIsForm:YES];
}

- (void)initAry:(NSArray *)arr{
    
    NSMutableArray *array1 = [NSMutableArray array];
    
    for (int i =0;i<arr.count; i++) {
        
        NSMutableArray *array2 = [NSMutableArray array];
        
        NSMutableDictionary *muDic = [[NSMutableDictionary alloc]init];
        
        QuestionModel *md = [QuestionModel mj_objectWithKeyValues:arr[i]];
        [muDic setObject:md.arrow forKey:@"arrow"];
        [muDic setObject:md.slender forKey:@"slender"];
        
        NSArray *listAry = arr[i][@"apprehend"];
        
        for (int j=0; j<listAry.count; j++) {
            
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            
            QuestionListModel *model = [QuestionListModel mj_objectWithKeyValues:listAry[j]];
            [dic setObject:model.lord forKey:@"lord"];
            [dic setObject:model.hydrogen forKey:@"hydrogen"];
            
            [dic setObject:@NO forKey:@"isShow"];
            
            [array2 addObject:dic];
        }
        
        [muDic setObject:array2 forKey:@"apprehend"];
        
        [array1 addObject:muDic];
        
    }
    
    self.changeArr = [NSMutableArray arrayWithArray:array1];
    self.data = [QuestionModel mj_objectArrayWithKeyValuesArray:arr];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    QuestionModel *mm = self.data[section];
    return mm.apprehend.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QuestionListTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    QuestionModel *mm  = self.data[indexPath.section];
    
    if (indexPath.row < mm.apprehend.count) {
        cell.model = mm.apprehend[indexPath.row];
        
        if (indexPath.row == mm.apprehend.count - 1) {
            cell.bottomV.hidden = YES;
        } else {
            cell.bottomV.hidden = NO;
        }
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    QuestionListTableCell *selCell = [tableView cellForRowAtIndexPath:indexPath];
    QuestionListModel *mm = selCell.model;
    
    
    QuestionModel *quesM = self.data[indexPath.section];
    
    NSMutableDictionary *muDic = [[NSMutableDictionary alloc]init];
    [muDic setObject:quesM.slender forKey:@"slender"];
    [muDic setObject:quesM.arrow forKey:@"arrow"];
    
    NSMutableArray * array = [NSMutableArray arrayWithArray:quesM.apprehend];
    
    for (int i=0; i<array.count; i++) {
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        
        QuestionListModel *mm = [QuestionListModel mj_objectWithKeyValues:array[i]];
        [dic setObject:mm.lord forKey:@"lord"];
        [dic setObject:mm.hydrogen forKey:@"hydrogen"];
        
        if (i == indexPath.row) {
            [dic setObject:@YES forKey:@"isShow"];
        } else {
            [dic setObject:@NO forKey:@"isShow"];
        }
        [array replaceObjectAtIndex:i withObject:dic];
        
        [muDic setObject:array forKey:@"apprehend"];
    }
    
    [self.changeArr replaceObjectAtIndex:indexPath.section withObject:muDic];
    
    self.data = [QuestionModel mj_objectArrayWithKeyValuesArray:self.changeArr];
    
    [self.tableView reloadData];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    QuestionSectionView *sectionHeaderView = [[QuestionSectionView alloc] init];
    
    QuestionModel *mm = self.data[section];
    
    sectionHeaderView.titleLab.text = [NSString stringWithFormat:@"%ld.%@",section+1,esString(mm.arrow)];
    sectionHeaderView.iconV.image = [UIImage imageNamed:@"icon_ques2"];
    
    if (section == 0) {
        sectionHeaderView.topBackV.hidden = YES;
    } else {
        sectionHeaderView.topBackV.hidden = NO;
    }
    
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    QuestionModel *mm = self.data[section];
    CGSize size = [NSString textSizeWithText:esString(mm.arrow) font:[UIFont fontWithName:kFuturaBold size:14] numberOfLines:0 lineSpacing:3 constrainedWidth:kScreenWidth - 45 - 5 - 36];
    return 15 + 15 + size.height + 2 + 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *sectionFooterView = [[UIView alloc] init];
    return sectionFooterView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001f;
}

- (void)clickSubmit{
    
    NSMutableArray *dataSelectAry = [[NSMutableArray alloc] init];
    for (int k=0; k<self.changeArr.count; k++) {
        QuestionModel *model = [QuestionModel mj_objectWithKeyValues:self.changeArr[k]];
        for (int j=0; j<model.apprehend.count; j++) {
            QuestionListModel *mm = [QuestionListModel mj_objectWithKeyValues:model.apprehend[j]];
            if (mm.isShow == YES) {
                
                QuestionUploadModel *mod = [[QuestionUploadModel alloc] init];
                mod.lord = mm.lord;
                mod.slender = model.slender;
                
                [dataSelectAry addObject:mod];
                
            }
        }
    }
    
    if (dataSelectAry.count == 0 || dataSelectAry.count != self.data.count) {
        [BoxLoadingHelper showBoxWithMessage:@"Please choice"];
        return;
    }
    NSString *string =  [dataSelectAry componentsJoinedByString:@"\n"];
    
    NSMutableDictionary *muDic = @{
        @"clip":string,
    }.mutableCopy;
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    [HttpNetHelper postNetworkHelperForPath:kSaveQuestionUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        [self.navigationController popViewControllerAnimated:YES];
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:YES];
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
